package com.huan.demo.handler;

import com.huan.demo.message.LoginRequestMessage;
import com.huan.demo.message.LoginResponseMessage;
import com.huan.demo.server.service.UserServiceFactory;
import com.huan.demo.server.session.Session;
import com.huan.demo.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {

        boolean login = UserServiceFactory.getUserService().login(msg.getUsername(), msg.getPassword());
        LoginResponseMessage loginResponseMessage = new LoginResponseMessage();
        if (login) {
            SessionFactory.getSession().bind(ctx.channel(),msg.getUsername());
            loginResponseMessage.setSuccess(true);
            loginResponseMessage.setReason("登录成功");

        } else {
            loginResponseMessage.setSuccess(false);
            loginResponseMessage.setReason("登录失败");
        }

        ctx.writeAndFlush(loginResponseMessage);
    }
}
